const express = require('express');
const router = express.Router();
const { Chapter, Course } = require('../../models');
const { Op, where } = require('sequelize');
const { NotFound, Conflict, BadRequest } = require('http-errors');
const { success, failure } = require('../../utils/responses');

/**
 * 白名单参数过滤
 * */
const filterBody = (data) => {
  return {
    courseId: data.courseId,
    title: data.title,
    content: data.content,
    video: data.content,
    rank: data.rank,
    free: data.free,
  };
};
const conditionParam = {
  attributes: { exclude: ['CourseId'] },
  include: [
    {
      model: Course,
      as: 'course',
      attributes: ['id', 'name'],
    },
  ],
};
/**
 * 公共方法: 查询当前章节
 * */

async function getChapter(req) {
  const { id } = req.params;
  const chapter = await Chapter.findByPk(id, conditionParam);
  if (!chapter) {
    throw new NotFound(`ID: ${id}的章节为找到`);
  }
  return chapter;
}

/**
 * 查询章节列表
 * */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    // 当前第几页，如果不传默认第一页
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    // 当前多少条数据，如果不传默认10条数据
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    // 计算offset
    const offset = (currentPage - 1) * pageSize;
    if (!query.courseId) {
      throw new BadRequest('获取章节列表失败， 课程不存在');
    }
    const condition = {
      ...conditionParam,
      where: {},
      order: [
        ['ranK', 'ASC'],
        ['id', 'DESC'],
      ],
      limit: pageSize,
      offset,
    };

    const title = decodeURIComponent(query.title);
    if (title) {
      condition.where.title = {
        [Op.like]: `%${title}%`,
      };
    }
    if (query.courseId) {
      condition.where.courseId = {
        [Op.eq]: query.courseId,
      };
    }
    console.log(condition, 'condition');
    // const chapters = await Chapter.findAll(condition);
    const { count: total, rows } = await Chapter.findAndCountAll(condition);
    success(res, '查询成功', {
      chapters: rows,
      pagination: {
        total,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询章节详情
 * */
router.get('/:id', async function (req, res) {
  try {
    const chapters = await getChapter(req);
    success(res, '查询成功', { chapters });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建章节
 * */
router.post('/', async function (req, res) {
  try {
    const body = filterBody(req.body);
    // 创建章节并对课程章节数量+1
    const chapters = await Chapter.create(body);
    await Course.increment('chaptersCount', { where: { id: chapter.courseId } });
    success(res, '创建成功', { chapters }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除章节
 * */
router.delete('/:id', async function (req, res) {
  try {
    const chapter = await getChapter(req);
    // 删除章节并对课程章节-1
    await chapter.destroy();
    await Course.decrement('chaptersCount', { where: { id: chapter.courseId } });
    success(res, '删除成功');
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新章节
 * */
router.put('/:id', async function (req, res) {
  try {
    const chapter = await getChapter(req);
    const body = filterBody(req.body);
    const data = await chapter.update(body);
    success(res, '更新成功', data);
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
